package com.wsjzzcbq.qianyuan.common.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.wsjzzcbq.qianyuan.common.bean.R;
import com.wsjzzcbq.qianyuan.common.cache.CacheService;
import com.wsjzzcbq.qianyuan.common.constant.CacheConsts;
import com.wsjzzcbq.qianyuan.common.constant.MsgConsts;
import com.wsjzzcbq.qianyuan.common.constant.SysConsts;
import com.wsjzzcbq.qianyuan.common.util.RequestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * UploadFileInterceptor 上传文件拦截器
 *
 * @author wsjz
 * @date 2022/03/16
 */
public class UploadFileInterceptor implements HandlerInterceptor {

    @Autowired
    private CacheService cacheService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if ("OPTIONS".equals(request.getMethod())) {
            return true;
        }

        String token =  RequestUtils.getHeaderByName(SysConsts.HEADER_TOKEN);
        if (StringUtils.isBlank(token) || cacheService.get(CacheConsts.userKey(token)) == null) {
            return401(response);
            return false;
        }
        return true;
    }

    private void return401(HttpServletResponse response) throws IOException {
        response.setCharacterEncoding(StandardCharsets.UTF_8.name());
        response.setContentType("application/json; charset=utf-8");
        response.getWriter().append(JSONObject.toJSONString(R.custom(3, MsgConsts.ILLEGAL_ACCESS, null)));
    }
}
